package HighLevelFunction

object partiaFunction {
  /**
   * 偏函数主要利用模式匹配对输入的参数做更精细的检查
   * def 偏函数名:PartialFunction[参数类型，返回值类型]={case语句},PartialFunction为偏函数类型，直接用
   * 偏函数只能匹配部分数据
   */
  def main(args: Array[String]): Unit = {
    val list: List[(String, Int)] = List(("a", 1), ("b", 2), ("c", 3), ("a", 12))
    //map转换，实现key不变，value变成2倍
    val newList: List[(String, Int)] = list.map(tuple => (tuple._1, tuple._2 * 2))
    println(newList)
    //用模式匹配对元组元素赋值，实现功能
    val newList2: List[(String, Int)] = list.map(
      tuple => {
        tuple match {
          case (word, count) => (word, count * 2)
        }
      }
    )
    println(newList2)
    //省略lamba表达式的写法，进行简化
    val newList3: List[(String, Int)] = list.map(
      {
        case (word, count) => (word, count * 2)
      }
    )
    println(newList3)
    //求绝对值用偏函数
    /**
     * 输入：正数，0，负数
     */
    val positiveAbs: PartialFunction[Int, Int] = {
      case x if x > 0 => x
    }
    val negativeAbs: PartialFunction[Int, Int] = {
      case x if x < 0 => -x
    }
    val zeroAbs:PartialFunction[Int,Int]={
      case 0=>0
    }
    def abs(x:Int):Int=(positiveAbs orElse negativeAbs orElse zeroAbs)(x)
    println(abs(-12))


  }

}
